//
//  XZCustomCamera.m
//  XZRun
//
//  Created by 何典钊 on 2017/3/13.
//  Copyright © 2017年 hedianzhao. All rights reserved.
//

#import "XZCustomCamera.h"

@interface XZCustomCamera ()

/* <#type#> **/
@property (nonatomic, strong) UIView *perView;

/* 输出设备 **/
@property (nonatomic, strong) AVCaptureStillImageOutput *captillImageOutput;

/* 输入设备 **/
@property (nonatomic, strong) AVCaptureDeviceInput *deviceInput;

/* <#type#> **/
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *perviewLayer;

/* 拍摄会话 **/
@property (nonatomic, strong) AVCaptureSession *capSession;
@end

@implementation XZCustomCamera

- (instancetype)initWithPerView:(UIView *)perview {
    
    self = [super init];
    _perView = perview;
    [self curretCamera];
    return self;
}

/// 初始化相机
- (void)curretCamera {
    
    // 1. 拿到输出设备
    __block AVCaptureDevice *capdevice;
    NSArray *arr = [AVCaptureDevice devices];
    
    [arr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        AVCaptureDevice *device = (AVCaptureDevice *)obj;
        
        if (device.position == AVCaptureDevicePositionBack) {
            capdevice = device;
        }
    }];
    
    // 2.
    
    _deviceInput = [[AVCaptureDeviceInput alloc] initWithDevice:capdevice error:nil];
    _captillImageOutput = [[AVCaptureStillImageOutput alloc] init];
    _capSession = [[AVCaptureSession alloc] init];
    
    if ([_capSession canAddInput:_deviceInput]) {
        [_capSession addInput:_deviceInput];}
    if ([_capSession canAddOutput:_captillImageOutput]) {
        [_capSession addOutput:_captillImageOutput];
    }
    
    _perviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_capSession];
    _perviewLayer.bounds = _perView.bounds;
    _perviewLayer.position = _perView.center;
    
    [_perView.layer insertSublayer:_perviewLayer atIndex:0];
    _perviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    [self start];
}

- (UIImage *)cutImageWithImage:(UIImage *)image {
    
    UIGraphicsBeginImageContext(_perView.frame.size);
    UIGraphicsGetCurrentContext();
    CGFloat width = [UIScreen mainScreen].bounds.size.width - _perView.bounds.size.width;
    CGFloat height = [UIScreen mainScreen].bounds.size.height - _perView.bounds.size.height;
    
    [image drawInRect:CGRectInset(_perView.frame, -width*0.5, -height*0.5)];
    [[NSNotificationCenter defaultCenter] postNotificationName:kWaterChangeDrawinrectImage object:nil];
    UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return resultImage;
}

- (void)captureImageCompletion:(void (^)(UIImage *))completion errorCallback:(void (^)(NSError *))errorCallback {
    
    NSArray *arr = _captillImageOutput.connections;
    AVCaptureConnection *connection = arr[0];
    
    [_captillImageOutput captureStillImageAsynchronouslyFromConnection:connection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
        
        if (error != nil) {
            NSLog(@"输出设备坏了");
        }
        NSData *data = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
        UIImage *image = [UIImage imageWithData:data];
        
        if (completion) {
            completion([self cutImageWithImage:image]);
        }
        
        if (errorCallback) {
            
            UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinsishSavingWithError:contxtInfo:), (__bridge void * _Nullable)(errorCallback));
        }
        
    }];
}

- (void)image:(UIImage *)image didFinsishSavingWithError:(NSError *)error contxtInfo:(void *)contxtinfo {
    void(^black)(NSError *error) = (__bridge void (^)(NSError *__strong))(contxtinfo);
    black(error);
    
    if (error == nil) {
        NSLog(@"成功");
    }
}

/// 切换摄像头
- (void)changeCamera {
    // 1. 获取当前摄像头的方向
    AVCaptureDevicePosition currentPosition = _deviceInput.device.position;
    
    __block AVCaptureDevice *capdevice;
    NSArray *arr = [AVCaptureDevice devices];
    
    [arr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        AVCaptureDevice *device = (AVCaptureDevice *)obj;
        AVCaptureDevicePosition position = device.position;
        if (currentPosition == AVCaptureDevicePositionBack) {
            
            if (position == AVCaptureDevicePositionFront) {
                capdevice = device;
            }
        } else {
            if (position == AVCaptureDevicePositionBack) {
                capdevice = device;
            }
        }
    }];
    
    AVCaptureDeviceInput *deviceInput = [[AVCaptureDeviceInput alloc] initWithDevice:capdevice error:nil];
    [_capSession removeInput:_deviceInput];
    
    if ([_capSession canAddInput:deviceInput]) {
        [_capSession addInput:deviceInput];
    }
    _deviceInput = deviceInput;
    [self start];
}

- (void)start {
    [_capSession startRunning];
}

- (void)stop {
    [_capSession stopRunning];
}

@end
